// import express from 'express'
const express = require('express')
// 安装 multer 用于文件上传
const multer = require('multer')
const fs = require('fs')


const app = express()


const adminLogin = require('./data/admin.json')


/* 
    文件上传
*/

let uploading = multer({
  dest: "./mock/upload",
  // 设定限制，每次最多上传1个文件，文件大小不超过1MB
  limits: { fileSize: 10000000, files: 1 },
  fileFilter(req, file, callback) {
    // 解决中文名乱码的问题
    file.originalname = Buffer.from(file.originalname, "latin1").toString(
      "utf8"
    );
    callback(null, true);
  },
})

app.post('/upload', uploading.single('file'), (req, res) => {
    // console.log(req.file)
    fs.renameSync(req.file.path, `./mock/upload/${req.file.originalname}`)// 修改文件名
    res.send(req.file)
})


/* 
    文件下载
*/
app.get("/download", (req, res) => {
    const url = req.query.filename
    console.log(url)
    url ? res.download(`./mock/upload/${url}`) : res.send({
        success: false,
        message: '没有文件'
    })
})


const url = require('url')

app.get("/login", (req, res) => {
    const user = url.parse(req.url, true).query.user
    const password = url.parse(req.url, true).query.password
    console.log(user)
    if (user === 'admin' && password === '1234') {
        res.send(adminLogin)
    } else {
        // res.send(otherUsers)
        return res.status(401).send({
            message: '用户名或密码错误'
        })
    }
})

// app.post("/login", (req, res) => {


// })



app.listen(3300, () => {
    console.log("服务器运行在 3300");
})